/*
 * Copyrignt (c) doubimeizhi.com. All Rights Reserved.
 * Author: mr.gao<fbg@live.com>
 * Created Time: 2016-12-07 15:06
 * Last Modified: 2017-07-28 14:34:45
 * File Name: qkcoupon/controllers/restore_coupon.go
 * Description:
 */

package controllers

import (
	"encoding/json"
	"qkcoupon/db"
	"qkcoupon/errorcode"
	"qkcoupon/rpc/client/passport"

	"qkcoupon/models"

	log "github.com/cihub/seelog"
)

type RestoreCouponController struct {
	//SCLoginedController
	URLSignController
}

// @router /restore [post]
func (p *RestoreCouponController) RestoreCoupon() {
	defer p.Output("RestoreCoupon")

	uid := p.GetString("uid")
	if uid == "" {
		log.Warn("uid==''")
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	up, errCode := passport.GetUserProfileByUID(uid)
	if errCode != errorcode.EC_GL_SUCCESS || up.Mobile == "" {
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	data := p.Ctx.Input.RequestBody
	if len(data) == 0 {
		log.Warn("len(data) == 0")
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	log.Debug(string(data))

	rp := &models.PSQkCouponRestoreParam{}
	err := json.Unmarshal(data, rp)
	if err != nil {
		log.Warn("Unmarshal failed!")
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	log.Debug(rp)

	if rp.Ccode == "" {
		log.Warn("rp.Ccode==\"\"")
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	errCode = db.SetCouponCState(uid, up.Mobile, rp.Ccode, int32(models.EQKCOUPON_CSTATE_NOTUSED))
	if errCode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errCode
		return
	}

	p.Resp["code"] = errorcode.EC_GL_SUCCESS
}
